package com.mine.modules.vm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mine.common.utils.oConvertUtils;
import com.mine.modules.sys.utils.ListUtils;
import com.mine.modules.vm.entity.VmPermissionLayer;
import com.mine.modules.vm.mapper.VmPermissionLayerMapper;
import com.mine.modules.vm.service.IVmPermissionLayerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 场景菜单 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-15
 */
@Service
public class VmPermissionLayerServiceImpl extends ServiceImpl<VmPermissionLayerMapper, VmPermissionLayer> implements IVmPermissionLayerService {

    @Override
    public void savePermissionLayers(String menuId, String layerIds, String lastLayerIds) {
        List<String> add = ListUtils.getDiff(lastLayerIds, layerIds);
        if (add != null && !add.isEmpty()) {
            List<VmPermissionLayer> list = new ArrayList<>();
            for (String p : add) {
                if (oConvertUtils.isNotEmpty(p)) {
                    VmPermissionLayer vmPermissionLayer = lambdaQuery()
                            .eq(VmPermissionLayer::getMenuId, menuId)
                            .eq(VmPermissionLayer::getLayerId, p).one();
                    if (vmPermissionLayer == null) {
                        VmPermissionLayer permissionLayer = new VmPermissionLayer(menuId, p);
                        list.add(permissionLayer);
                    }
                }
            }
            this.saveBatch(list);
        }
        List<String> delete = ListUtils.getDiff(layerIds, lastLayerIds);
        if (delete != null && !delete.isEmpty()) {
            for (String layerId : delete) {
                this.remove(new QueryWrapper<VmPermissionLayer>().lambda().eq(VmPermissionLayer::getMenuId, menuId).eq(VmPermissionLayer::getLayerId, layerId));
            }
        }
    }

    @Override
    public List<String> getLayerIdsByMenuIds(List<String> menuIds) {
        return lambdaQuery()
                .in((menuIds != null && !menuIds.isEmpty()), VmPermissionLayer::getMenuId, menuIds)
                .list()
                .stream()
                .map(VmPermissionLayer::getLayerId)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getLayerIdsByMenuId(String menuId) {
        return lambdaQuery()
                .eq(VmPermissionLayer::getMenuId, menuId)
                .list()
                .stream()
                .map(VmPermissionLayer::getLayerId)
                .collect(Collectors.toList());
    }
}
